<?php
namespace app\models;

use Yii;
use yii\base\Model;

/**
 * 用户注册表单
 *
 * Class UserRegisterForm
 * @package app\models
 */
class UserRegisterForm extends Model
{
    public $mobile;
    public $mobile_code;
    public $nickname;
    public $password;

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'mobile'=>'手机号码',
            'mobile_code'=>'手机验证码',
            'nickname'=>'昵称',
            'password'=>'密码',
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['mobile', 'mobile_code', 'nickname', 'password'], 'required'],
            ['mobile', 'match', 'pattern'=>'/^\d{11}$/'],
            ['mobile_code', function($attribute, $params) {
                if (!Sms::checkCode($this->mobile, Sms::TYPE_REG, $this->mobile_code)) {
                    $this->addError('mobile_code', '验证码错误。');
                }
            }],
            ['mobile', 'unique', 'targetClass'=>User::className(), 'filter'=>['<>', 'status', User::STATUS_DELETED]]
        ];
    }

    /**
     * 用户注册
     * @return boolean
     */
    public function register()
    {
        if (!$this->validate()) {
            return false;
        }
        $user = new User();
        $user->nickname = $this->nickname;
        $user->password = Yii::$app->security->generatePasswordHash($this->password);
        $user->mobile = $this->mobile;
        $user->type = User::TYPE_COMMON; // 默认用户类型
        $user->status = User::STATUS_ACTIVE;
        $user->create_time = time();
        $user->last_login_type = $user->type;
        $r = $user->save();
        if ($r) {
            Yii::$app->user->login($user); // 会话登录
            return true;
        }
        $this->addErrors($user->errors);
        return false;
    }
}
